package com.littleken.foodieCommon.configuration;

import com.littleken.foodieCommon.Response.ServerResponse;
import com.littleken.foodieCommon.Utils.SerializeUtil;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/*
 * 错误统一处理controller
 * Create by littleken on 2020/11/23 15:21
 */
@RestController
@RequestMapping("${server.error.path:${error.path:/error}}")
public class ExceptionController extends BasicErrorController {

    public ExceptionController(ErrorAttributes errorAttributes,
                               @Qualifier("goffErrorProperties") GoffErrorProperties errorProperties) {
        super(errorAttributes, errorProperties);
    }

    @Override
    public ModelAndView errorHtml(HttpServletRequest request,
                                  HttpServletResponse response) {
        HttpStatus status = getStatus(request);
        SerializeUtil.writeResponse(response, new ServerResponse<>(status.value(), status.getReasonPhrase()));
        return null;
    }

    //注意这里捕获的是接口实现里没有捕获的异常，如果已经捕获了，这里不可能执行
    @RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = new HashMap<String, Object>();
        HttpStatus status = getStatus(request);
        body.put("errcode", status.value());
        body.put("errmsg", status.getReasonPhrase());
        return new ResponseEntity<>(body, status);
    }

}

